using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Net;
using Mailias.UI.Web.Infrastructure;

namespace Mailias.UI.Web
{
    public class SMTPServerSettings
    {
        public object DocumentStore { get; set; }

        public int Port { get; set; }

        private IPAddress _ipAddress;
        public IPAddress IpAddress
        {
            get { return _ipAddress; }
            private set { _ipAddress = value; }
        }

        public SMTPServerSettings(SmtpSettings settings)
        {
            _ipAddress = ConvertStringToIPAddress(settings.Address);
            Port = settings.Port;
        }

        public SMTPServerSettings(string address, int port, object documentStore)
        {
            _ipAddress = ConvertStringToIPAddress(address);
            Port = port;
            DocumentStore = documentStore;
        }


        private IPAddress ConvertStringToIPAddress(string address)
        {
            var parts = address.Split('.');
            if (parts.Length != 4)
            {
                throw new ArgumentException(string.Format(@"The address - {0} - does not have enough octets.", address));
            }
            var bytes = new byte[4];
            bool gotBytes = true;
            int i = 0;
            while (i < 4 && gotBytes)
            {
                if (!Byte.TryParse(parts[i], out bytes[i]))
                    gotBytes = false;
                i++;
            }

            if (gotBytes && i >=4)
            {
                return new IPAddress(bytes);
            }

            throw new ArgumentException(string.Format(@"Unable to convert octet {0} ({1})", i+1, parts[i]));
        }
    }
}